# This file is a part of Conspire
# $Id: views.py 64 2007-04-23 20:47:44Z b.ghose $

from django import newforms as forms
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Context, loader
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.mail import send_mail
from django.contrib.sites.models import Site
from freedel.conspire.models import Talk, Feedback, Speaker, LEVELS
from django.template import RequestContext

from forms import RegistrationForm, TalkSubmissionForm, FeedbackForm
from models import Category, UserProfile, PresentationFiles, Talk

from freedel.contentstore import add_content

def activate(request, activation_key):
    activation_key = activation_key.lower()
    user = UserProfile.objects.filter(activation_key=activation_key)
    if user and not user[0].activation_key_expired(activation_key):
        user = user[0]
        user.is_active = True
        user.save()
        return render_to_response('simple_message.html',
                                  {'message' :"You have successfully completed your registration.",},
                                  RequestContext(request))
    else:
        return render_to_response('simple_message.html',
                                  {'message' :"You have followed an incorrect URL or your activation link has expired",},
                                  RequestContext(request))

def register(request):
    if request.user.is_authenticated():
        
        # They already have an account; don't let them register again
        return render_to_response('simple_message.html',
                                  {'message' :"You are already registered.",},
                                  RequestContext(request))

    form = None

    def update_track_info(regform):
        tracks = [str(i) for i in Category.objects.all()]
        tr = [(i,i) for i in tracks]
        regform.__dict__['fields']['tracks'].__dict__['widget'].__dict__['choices'] = tr
        regform.__dict__['fields']['tracks'].__dict__['_choices'] = tr

        return
    
    if request.POST:
        data = request.POST.copy()
        data.update(request.FILES)
        
        # check for validation errors (newforms)

        bound_form = RegistrationForm(data)
        update_track_info(bound_form)
        
        if bound_form.errors:
            form = bound_form
        else:
            data = bound_form.clean_data
            up = UserProfile.objects.create_user_profile(data)

            # TODO
            # 1. send activation mail

##             manipulator.do_html2python(data)
##             new_user = manipulator.save_user(data)

##             # Build the activation key for their account
##             salt = sha.new(str(random.random())).hexdigest()[:5]
##             activation_key = sha.new(salt+new_user.username).hexdigest()
##             key_expires = datetime.datetime.today() + datetime.timedelta(2)
##             new_user.activation_key = activation_key
##             new_user.key_expires = key_expires
##             new_user.save()

##             # Send Activation email to User
##             email_subject = 'Confirm your FreeDel \'07 Registration'
##             current_domain = Site.objects.get_current().domain
            
##             t = loader.get_template('registration_mail.txt')
##             c = Context({'full_name':new_user.user.get_full_name(),
##                          # FIXME: use get_profile() above
##                          'base_url':current_domain,
##                          'activation_key':new_user.activation_key
##                          })
##             email_body = t.render(c)
            
##             send_mail(email_subject,
##                       email_body,
##                       settings.EMAIL,
##                       [new_user.email])

            return HttpResponseRedirect('/simple/post_registration/')
    else:

        form = RegistrationForm()
        update_track_info(form)
    
    return render_to_response('register.html',
                              {'form' : [form[i] for i in form.fields]},
                              RequestContext(request))

def post_registration(request):

    msg = """A mail has been sent to
    your inbox. Please follow the link in the
    mail to activate your
    account. If you do not see the
    mail even after a while, please
    check your Spam folder."""
    
    return render_to_response('simple_message.html',
                              {'message' : msg},
                              RequestContext(request))
                              
def index(request):
    return render_to_response('index.html', {}, RequestContext(request))

def feedback(request):
    msg = "Thank you for your feedback."
    
    def update_talk_info(form):
        talks = [str(i) for i in Talk.objects.all()]
        tk = [(i,i) for i in talks]
        tk.insert(0, ('General', '----'))
        form.__dict__['fields']['talks'].__dict__['widget'].__dict__['choices'] = tk
        form.__dict__['fields']['talks'].__dict__['_choices'] = tk
        return

    if not request.POST:
        form = FeedbackForm()

    else:
        data = request.POST.copy()
        bound_form = FeedbackForm(data)
        update_talk_info(bound_form)
        
        if not bound_form.is_valid():
            form = bound_form

        else:
            d = bound_form.clean_data
            if d['talks'] == 'General':
                talk = None
            else:
                talk = Talk.objects.get(talk_name=d['talks'])
            
            f =  Feedback(sender=d['username'], email=d['email'], talk=talk,
                          feedback=d['feedback'])
            f.save()
            return render_to_response('simple_message.html',
                                      {'message' : msg},
                                      RequestContext(request))
    update_talk_info(form)
    return render_to_response('feedback.html',
                              {'form' : [form[i] for i in form.fields]},
                              RequestContext(request))

def submit_talk(request):
    if not request.user.is_authenticated():
        return render_to_response('error.html', {'error':'''Please <a href="/login/">login</a> first.'''}, RequestContext(request))

    try:
        # FIXME: Somebody fix this shit
        # See if the user who is logged in is a speaker
        user = User.objects.get(username=request.user.username)
        userp = UserProfile.objects.get(user=user)
        spk = Speaker.objects.get(user=userp)
    except:
        return render_to_response('error.html', {'error':'''You need to be registered as a
                                                 speaker to be able to submit a talk proposal.'''}, RequestContext(request))

    def update_category_info(regform):
        tracks = [str(i) for i in Category.objects.all()]
        tr = [(i,i) for i in tracks]
        regform.__dict__['fields']['category'].__dict__['widget'].__dict__['choices'] = tr
        regform.__dict__['fields']['category'].__dict__['_choices'] = tr

    if not request.POST:
        form = TalkSubmissionForm()
        update_category_info(form)
    
        return render_to_response('submit.html',
                                  {'form':[form[i] for i in form.fields]}, RequestContext(request))
    else:
        data = request.POST.copy()
        data.update(request.FILES)
        bound_form = TalkSubmissionForm(data)
        update_category_info(bound_form)

        if not bound_form.is_valid():
            return render_to_response('submit.html',
                                      {'form':[bound_form[i] for i in bound_form.fields]}, RequestContext(request))

        # everything is alright, so create a talk and associate the
        # talk to the speaker object

        d = bound_form.clean_data
        
        # Fetch the relevant Category object using d['category']
        category = Category.objects.get(name=d['category'])
        
        talk = Talk(talk_name=d['name'], abstract=d['abstract'],
                    category=category, equipment=d['equipment'],
                    level=d['level'], comments=d['comments'])

        talk.add_presentation_file(data['presentation_file']['content'])
        talk.save()

        # Associate the talk object to the speaker in question
        spk.registered_talks.add(talk)
        spk.save()

        form = TalkSubmissionForm()
        return render_to_response('submit.html', {'form':[form[i] for i in form.fields],
                                                  'success':'Your talk proposal has been submitted.'}, RequestContext(request)) 
        

def my_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect("/")
    
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect("/")                
            else:
                return render_to_response('login.html', {'error':'Your account has been disabled.'}, RequestContext(request))
        else:
            return render_to_response('login.html', {'error':'The username and password you supplied do not match. Please try again.'}, RequestContext(request))
    else:
        return render_to_response('login.html', {}, RequestContext(request))

def my_logout(request):
    logout(request)
    return HttpResponseRedirect("/")    

def talks(request):
    talks = Talk.objects.all()
    return render_to_response('talks.html', {'talks':talks}, RequestContext(request))

def talk(request, talk_id):
    return render_to_response('error.html', {'error':"Not implemented yet."}, RequestContext(request))

def speakers(request):
    return render_to_response('error.html', {'error':"Not implemented yet."}, RequestContext(request))
